package com.haizi.battery.gate.server.handler;

import com.haizi.battery.gate.core.base.AbstractBusinessHandler;
import com.haizi.battery.gate.core.base.IHandler;
import com.haizi.battery.gate.core.evgb.entity.EvGBProtocol;
import com.haizi.battery.gate.core.evgb.enumtype.CommandType;
import com.haizi.battery.gate.server.common.CommonCache;
import com.haizi.battery.gate.server.enumtype.EvGBHandlerType;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

/**
 * 业务处理核心类
 * created by dyy
 */
@Service
public class BusinessHandler extends AbstractBusinessHandler implements ApplicationContextAware {

    private static final Logger logger = LoggerFactory.getLogger(BusinessHandler.class);

    private ApplicationContext applicationContext;

    @Autowired
    private DebugHandler debugHandler;

    @Override
    public void doBusiness(EvGBProtocol protocol, Channel channel) {
        debugHandler.debugger(protocol);
        EvGBHandlerType evGBHandlerType = EvGBHandlerType.valuesOf(protocol.getCommandType().getId());
        if(evGBHandlerType.getHandler()!=null){
            if(protocol.getCommandType() != CommandType.VEHICLE_LOGIN) {
                Channel channel1 = CommonCache.vinChannelMap.get(protocol.getVin());
                if (channel1 == null || !channel1.isOpen() || !channel1.isActive() ) {
                    channel.close();
                    logger.info("已经断开连接 踢下线 {}", protocol.getVin());

                }
            }
            IHandler handler = (IHandler) applicationContext.getBean(evGBHandlerType.getHandler());
            handler.doBusiness(protocol,channel);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
